package org.example.springbootrabbitmq.confirm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/confirm")
public class ConfirmController {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @RequestMapping("/sendMessage/{message}")
    public String confirm(@PathVariable String message) {

        // 交换机异常，消息不丢失
        CorrelationData correlationData1 = new CorrelationData("1");
        rabbitTemplate.convertAndSend(ConfirmConfig.EXCHANGE_NAME, ConfirmConfig.ROUTING_KEY, message+"key1",correlationData1);
        log.info("当前时间：{},消息体：,{}", new Date(),message);

        // 通过修改发送的路由key，模拟交换机正常，队列异常，发现消息依然丢失
        // 说明光有消息确认机制是不够的，还需要消息回退机制
        CorrelationData correlationData2 = new CorrelationData("2");
        rabbitTemplate.convertAndSend(ConfirmConfig.EXCHANGE_NAME, ConfirmConfig.ROUTING_KEY+1, message+"key2",correlationData2);
        log.info("当前时间：{},消息体：,{}", new Date(),message);
        return "confirm";
    }
}
